#include"buffer_define.h"

_FILE* _fopen(const char *path, const char *mode){
	int flags = 0;

	if (strcmp(mode, "r") == 0) {
		flags = O_RDONLY;
	}
	else if (strcmp(mode, "w") == 0) {
		flags = O_WRONLY | O_CREAT | O_TRUNC;
	}
	else if (strcmp(mode, "a") == 0) {
		flags = O_WRONLY | O_CREAT | O_APPEND;
	}

	_FILE *fp = (_FILE*)malloc(sizeof(_FILE));
	if (fp == NULL) assert(fp != NULL);

	fp->fd = open(path, flags);
	if (fp->fd < 0) { free(fp); return NULL;}
	
	fp->size = 0;
	fp->capacity = SIZE;
	fp->refresh_type = LINE_REFRESH;
	memset(fp->buffer, 0, sizeof(fp->buffer));
        
	return fp;
}


void _fclose(_FILE *fp) {
	
	if (fp->size > 0) write(1, fp->buffer, fp->size);
	fp->size = 0;
	free(fp);
	return ;
}

void _fwrite(void *str, size_t num, _FILE *fp) {
  dup2(fp->fd, 1);	
	if ((fp->size + num) <= fp->capacity) {
	    memcpy(fp->buffer + fp->size, str, num);
	    fp->size += num;
	}
	else {
            printf("buffer over\n");
	    return ;
	}

	switch(fp->refresh_type) {
	    
	    case NOW_REFRESH: {
	         write(1, fp->buffer, fp->size);
                 fp->size = 0;
		 break;
	    }

	    case LINE_REFRESH: {	 
		 if (fp->buffer[fp->size] == '\n') {
		    write(1, fp->buffer, fp->size);
		    fp->size = 0;
		 }   
		 break;
	    }
	
            case FULL_REFRESH: {
	         if (fp ->size >= fp->capacity) {
			 write(1, fp->buffer, fp->size);
			 fp->size  = 0;
		 }
		 break;
	    }

	    default: {
		 printf("error\n");
		 break;
	    }

        }

}


